﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using bts_webapp.Models;

namespace bts_webapp.Account
{
    public partial class Login : System.Web.UI.Page
    {
        private BTSModelDataContext _dataContext;
        /// <summary>
        /// Get the current db context.
        /// </summary>
        public BTSModelDataContext DbContext
        {
            get
            {
                if (_dataContext == null)
                {
                    _dataContext = new BTSModelDataContext();
                }
                return _dataContext;
            }
        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            //RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
        }

        protected void LoginUser_Authenticate(object sender, AuthenticateEventArgs e)
        {
            var users = this.DbContext.VIBA_Users.ToList();
            
            var userName = this.LoginUser.UserName.Trim();
            var password = this.LoginUser.Password.Trim();
            var user = users.FirstOrDefault(u => u.User_Id == userName && u.User_Pass == password && u.User_Status==1);
            if (user != null)
            {
                e.Authenticated = true;

                //setup user
                this.Session["CurrentUser"] = user;
                //setup permission
                var permissions = this.DbContext.VIBA_QUYENs.Where(x => x.User_Id == user.User_Id).ToList();
                if (permissions != null && permissions.Count > 0) 
                {
                    this.Session["PermissionList"] = permissions;    
                }

                Response.Redirect("~/Default.aspx", true);

                this.DbContext.Dispose();
            }
        }
    }
}
